package net.aiion.weave.impl.startup;

import net.aiion.weave.impl.startup.resources.StartupClassResourceListener;
import net.aiion.weave.spi.naming.GlobalContext;
import net.aiion.weave.spi.naming.GlobalContextFactory;
import net.aiion.weave.spi.naming.SessionContext;
import net.aiion.weave.spi.resources.Resource;
import net.aiion.weave.spi.resources.ResourceFinder;
import net.aiion.weave.spi.resources.ResourceFinderFactory;
import net.aiion.weave.spi.resources.ResourceListener;
import net.aiion.weave.spi.startup.GlobalContextStartup;
import net.aiion.weave.spi.startup.SessionContextStartup;

public class GlobalContextStartupImpl implements GlobalContextStartup {
    private final GlobalContext globalContext;

    public GlobalContextStartupImpl() {

        final ResourceFinder resourceFinder = ResourceFinderFactory.getInstance().createResourceFinder();
        resourceFinder.addResourceListener(new StartupClassResourceListener());
        resourceFinder.addResourceListener(new ResourceListener() {
            @Override
            public void onStartup() {
            }

            // Non-UI-Binder-Cards (aka XHTML-Cards)
            @Override
            public void resourceFound(final Resource aResource) {
                if (!aResource.getName().endsWith(".xhtml")) {
                    return;
                }

                // Let the card compile here
            }

            @Override
            public void onShutdown() {
            }
        });

        resourceFinder.findResources();

        // TODO Is all that reflection stuff really necessary? I mean, interfaces don't get modified during the
        // bootstrap process and should be loaded via the parent class loader of the BytecodeLoader.
        globalContext = GlobalContextFactory.getInstance().createGlobalContext();
    }

    @Override
    public String getGlobalContextId() {
        return globalContext.getId();
    }

    @Override
    public SessionContextStartup usingSessionContext(final String aSessionContextId) {
        return new SessionContextStartupImpl(lookupSessionContext(aSessionContextId));
    }

    private SessionContext lookupSessionContext(final String aSessionContextId) {
        return globalContext.lookupSessionContext(aSessionContextId);
    }

    @Override
    public void executeShutdown() {
        globalContext.dispose();
    }
}
